﻿using System;
using System.Collections.Generic;
using System.Linq;
using TaskKernel.Configuration;
using TaskKernel.DTO;
using TaskKernel.Infrastructure;

namespace TaskKernel.Domain.Services.Mail
{
    public class BodyTemplateChange : IBodyTemplate
    {
        private readonly string _bodyComplete;

        public BodyTemplateChange(Task task, string action)
        {
            var body = new List<string>();
            var link = task.Department.WebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + task.UID;

            body.Add("Действие: "+action);
            var firstEventOwner = task.GetUncommittedChanges().Select(x => x.Owner).FirstOrDefault();
            if (firstEventOwner != null)
                body.Add("Инициатор: " + firstEventOwner.FullName);
            if (task.Executor != null)
                body.Add("Ответственный: " + task.Executor.FullName);
            if (task.Owner != null)
                body.Add("Владелец: " + task.Owner.FullName);
            if (task.Participants.Any())
                body.Add("Участники: " + task.Participants.ToStringOverSemicolon());

            body.Add("Ссылка: " +
                         new LiteralHelper().SetLink(TaskKernelConfiguration.InnerServer + link).Insert(task.TaskName));
            body.Add("Ссылка в Интернете: " +
                     new LiteralHelper().SetLink(TaskKernelConfiguration.OutterServer + link).Insert(task.TaskName));
            var bodyin = new List<string>();
            if (task.GetUncommittedChanges().Any()){
                bodyin.Add("<table>");
                foreach (var @event in task.GetUncommittedChanges())
                {
                    var bodyPartTemplate = @"<tr><td valign=""top"">##DATECREATE##</td><td>##COMMENT##</td></tr>";
                    bodyPartTemplate = bodyPartTemplate.Replace("##DATECREATE##", @event.Time.ToString());
                    bodyPartTemplate = bodyPartTemplate.Replace("##COMMENT##", @event.Text);
                    bodyin.Add(bodyPartTemplate);   
                }
                bodyin.Add("</table>");
            }
            _bodyComplete = String.Join("<br>", body.ToArray())+String.Join("", bodyin.ToArray());
        }

        #region IBodyTemplate Members

        public string GetBody()
        {
            return _bodyComplete;
    }

        #endregion
    }
}